package com.example.store.controller;

import com.example.store.common.JsonResult;
import com.example.store.service.ex.*;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.ExceptionHandler;

public class BaseController  {
    /**操作成功状态码**/
    public static final int OK = 200;

    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> haleException(Throwable e){
        JsonResult<Void> result = new JsonResult<Void>(e);
        if(e instanceof UsernameDuplicatedException){
            result.setState(4000);
        }else if(e instanceof UsernameNotFoundException){
            result.setState(4001);
        }else if(e instanceof PasswordError){
            result.setState(4002);
        }else if(e instanceof InsertException){
            result.setState(4003);
        }else if(e instanceof UpdateException){
            result.setState(4004);
        }else if(e instanceof AddressCountLimitException){
            result.setState(4005);
        } else if (e instanceof  AddressNotFoundException) {
            result.setState(4006);
        } else if(e instanceof ProductNotFoundException){
            result.setState(4007);
        }else if (e instanceof AccessDeniedException){
            result.setState(4008);
        }else if (e instanceof CartNotFoundException){
            result.setState(4009);
        }

        return result;
    }

    /**
     * 从HttpSession中获取uid
     * @param httpSession
     * @return
     */
    protected final Integer getUidFromSession(HttpSession httpSession){
        return Integer.valueOf(httpSession.getAttribute("uid").toString());
    }

    /**
     *从HttpSession中获取username
     * @param httpSession
     * @return
     */
    protected final String getUsernameFromSession(HttpSession httpSession){
        return String.valueOf(httpSession.getAttribute("username").toString());
    }
}
